class SponsorsController < ApplicationController
  scaffold :sponsor
  
  def login
    case @request.method
      when :post
      if @session['user'] = User.authenticate(@params['user_login'], @params['user_password'])
        flash['notice']  = "Login successful"
        if @requestUrl = @session['requestUrl']
          redirect_to(@requestUrl)
        else
          redirect_back_or_default :action => "welcome"
        end
      else
        @login    = @params['user_login']
        @message  = "Login unsuccessful"
      end
    else
      @session['requestUrl'] = @request.env['HTTP_REFERER']  
    end
  end
  
  def logout
    @session['user'] = nil
  end
  
  def new
    @sponsor = Sponsor.new
    @user = User.new
    @user.sponsor = @sponsor
    @user
  end
  
  def create
    @user = User.new(params[:user])
    @sponsor = Sponsor.new(params[:sponsors])
    if @sponsor.save && @user.save
      @user.sponsor = @sponsor
      @session['user'] = User.authenticate(@user.login, @params['user']['password'])
      flash[:notice] = 'Sponsor was successfully created.'
      redirect_to :controller => 'children', :action => 'index'
    else
      render :action => 'new'
    end
  end
  
  def list 
    @sponsors_pages, @sponsors = paginate :sponsors, :per_page => 10
  end
  
  def sponsor_child
    @child_id = params[:id]
    @user = @session['user']
    if (@user==nil || @user.sponsor==nil)
      redirect_to :controller => "account", :action => "login"
    end
    @child_id
  end
  
  def record_sponsorship_level
    @sponsor_id = @session['user'].sponsor.id
    @child_id = params[:child_id]
    if @sponsor_payment = params[:sponsor_payment]
    else @sponsor_payment = params[:sponsor_payment_other]['other']
    end
    @child = Child.find(@child_id)
    
    if ((@child.sponsorship_needs - @sponsor_payment.to_i) < 0)
      @sponsor_payment = (@sponsor_payment.to_i + @child.sponsorship_needs).to_s
      @child.sponsorship_needs = 0
    else
      @child.sponsorship_needs -= @sponsor_payment.to_i
    end
    @child.save
    @sponsor_relationship = SponsorRelationship.new  
    @sponsor_relationship.support_payment = @sponsor_payment
    @sponsor_relationship.sponsor_id = @sponsor_id
    @sponsor_relationship.child_id = @child_id
    @sponsor_relationship.save
    @sum_of_support_payments = 0
    SponsorRelationship.find_all.each {|sponsor_relationship_local| 
      if(sponsor_relationship_local.sponsor_id == @sponsor_id) 
        @sum_of_support_payments += sponsor_relationship_local.support_payment
      else
        @sum_of_support_payments = 0
      end
    }
    #    SponsorRelationship.find_by_sql("select support_payment from sponsor_relationships where sponsor_id = #{@sponsor_id.to_s}").each {|support_payment| @sum_of_support_payments += support_payment}
    @sum_of_support_payments
  end
  
end
